package com.moss.cloud.base.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moss.cloud.base.api.model.from.TenantConfigFrom;
import com.moss.cloud.base.biz.mapper.TenantConfigMapper;
import com.moss.cloud.base.biz.model.TenantConfig;
import com.moss.cloud.base.biz.service.ITenantConfigService;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.utils.UserContextHolder;
import com.moss.cloud.common.security.annotation.RequiresTenant;
import com.moss.cloud.common.security.component.RedisTemplateOps;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 租户配置服务层实现
 *
 * @author 瑾年
 * @date 2023年3月23日
 */
@Service
public class TenantConfigServiceImpl extends ServiceImpl<TenantConfigMapper, TenantConfig> implements ITenantConfigService {
    private final RedisTemplateOps redisTemplateOps;

    public TenantConfigServiceImpl(RedisTemplateOps redisTemplateOps) {
        this.redisTemplateOps = redisTemplateOps;
    }

    /**
     * 通过租户ID查询租户配置
     *
     * @param tenantId
     * @param key
     * @return
     */
    @Override
    public TenantConfig getTenantConfig(Long tenantId, String key) {
        TenantConfig tenantConfig;
        Boolean hasKey = redisTemplateOps.hasKey(Constant.TENANT_CONFIG + tenantId + key);
        if (hasKey.equals(Boolean.TRUE)) {
            tenantConfig = (TenantConfig) redisTemplateOps.get(Constant.TENANT_CONFIG + tenantId + key);
        } else {
            tenantConfig = this.getOne(new QueryWrapper<TenantConfig>().lambda()
                    .eq(TenantConfig::getTenantId, tenantId).eq(TenantConfig::getConfigCode,key));
            redisTemplateOps.set(Constant.TENANT_CONFIG + tenantId, tenantConfig);
        }
        return tenantConfig;
    }

    /**
     * 查询租户配置列表
     *
     * @return
     */
    @Override
    @RequiresTenant
    public List<TenantConfig> tenantConfList(){
        return this.list(new QueryWrapper<TenantConfig>().lambda()
                .eq(TenantConfig::getTenantId, UserContextHolder.getTenantId()));
    }

    /**
     * 租户更新配置
     *
     * @param tenantConfigFrom
     * @return
     */
    @Override
    @RequiresTenant
    public boolean updateConfig(TenantConfigFrom tenantConfigFrom){
        TenantConfig tenantConfig = new TenantConfig();
        BeanUtils.copyProperties(tenantConfigFrom,tenantConfig);
        return this.updateById(tenantConfig);
    }
}
